#include"DList.h"

DListNode* BuyDListNode(DLTDataType x)
{
	DListNode* newnode = (DListNode*)malloc(sizeof(DListNode));
	if (newnode == NULL)
	{
		perror("BuyDListNode->malloc failed");
		exit(-1);
	}
	newnode->next = NULL;
	newnode->prev = NULL;
	newnode->data = x;
	return newnode;
}

DListNode* DLInit()
{
	DListNode* phead = (DListNode*)malloc(sizeof(DListNode));
	if (phead == NULL)
	{
		perror("DLInit->malloc failed");
		exit(-1);
	}
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void DLPushBack(DListNode* phead, DLTDataType x)
{
	assert(phead);
	DListNode* newnode = BuyDListNode(x);
	DListNode* tail = phead->prev;
	newnode->prev = tail;
	tail->next = newnode;
	newnode->next = phead;
	phead->prev = newnode;
}

void DLPrint(DListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	DListNode* cur = phead->next;
	printf("head<=>");
	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void DLPushFront(DListNode* phead, DLTDataType x)
{
	assert(phead);
	DListNode* newnode = BuyDListNode(x);
	DListNode* head = phead->next;
	newnode->next = head;
	newnode->prev = phead;
	phead->next = newnode;
	head->prev = newnode;
}

void DLPopBack(DListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	DListNode* tail = phead->prev->prev;
	DListNode* del = tail->next;
	tail->next = phead;
	phead->prev = tail;
	free(del);
}

void DLPopFront(DListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	DListNode* head = phead->next;
	phead->next = head->next;
	head->next->prev = phead;
	free(head);
}

void DLInsert(DListNode* pos, DLTDataType x)
{
	DListNode* newnode = BuyDListNode(x);
	DListNode* prev = pos->prev;
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void DLErase(DListNode* pos)
{
	assert(pos);
	DListNode* prev = pos->prev;
	DListNode* next = pos->next;
	free(pos);
	prev->next = next;
	next->prev = prev;
}

DListNode* DLFind(DListNode* phead, DLTDataType x)
{
	assert(phead);
	assert(phead->next != phead);
	DListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void DLDestroy(DListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	DListNode* cur = phead->next;
	DListNode* del = NULL;
	while (cur != phead)
	{
		del = cur;
		cur = cur->next;
		free(del);
	}
	free(cur);
}

